from flask import Flask, request, jsonify
import threading
import uuid
from queue import Queue
from typing import Dict

def create_http_server(ip: str, port: int, command_queue: Queue, result_queue: Queue, command_results: Dict[str, Dict[str, str]]) -> threading.Thread:
    """
    创建 HTTP 服务器线程。

    :param host: IP address for the HTTP server to bind to.
    :param port: Port number for the HTTP server to bind to.
    :param command_queue: 用于将 HTTP 请求传递给 main 的队列
    :param result_queue: 用于从 WebSocket 的队列中接收 main 请求结果
    :param command_results: 用于存储命令执行结果的字典
    :return: 线程对象
    """
    app = Flask(__name__)

    @app.route('/arm', methods=['POST'])
    def send_command():
        # 接收命令参数
        data = request.get_json()
        command = data.get('command')
        if not command:
            return jsonify({"code": 1, "message": "parameter 'command' not found"}), 400

        command_queue.put(command)
        try:
            result = result_queue.get(timeout=2)
            if "command" not in result or "id" not in result or result["command"] != command:
                print(f'Websocket client return error：{result}')
                return jsonify({"code": 2, "message": f'Websocket client return error：{result}'})
            else:
                print(f'Websocket client return ok：{result}')
                return jsonify({"code": 0, "command": result["command"], "id": result["id"], "message": f"Successfully send command '{command}'"})
        except Exception as e:
            print(f'send command "{command}" timeout to ws handler timeout')
            return jsonify({"code": 3, "message": f"Send command '{command}' to Websocket client timeout"})

    @app.route('/arm', methods=['GET'])
    def get_result():
        # 查询命令执行结果
        command_id = request.args.get('id')
        if not command_id:
            return jsonify({"code": 1, "message": "parameter 'id' not found"}), 400

        result = command_results.get(command_id)
        if result is None:
            return jsonify({"code": 2, "message": f"the result of command {command_id} not found"}), 200

        return jsonify({"code": result["code"], "id": command_id, "message": result["message"]})

    def run() -> None:
        app.run(host=ip, port=port)

    return threading.Thread(target=run, daemon=True)
